package com.wisdytech.linkdcs.equipment.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.wisdytech.common.bean.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.OrderType;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.thrift.api.LinkDCSService;
import com.wisdytech.common.thrift.service.ThriftClient;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.equipment.dao.IEqAutoAlarmRecordDao;
import com.wisdytech.linkdcs.equipment.dao.IEqClientDao;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.dto.EquipHistorySearchDTO;
import com.wisdytech.linkdcs.equipment.dto.EquipmentAuoAlarmDTO;
import com.wisdytech.linkdcs.equipment.model.AutoAlarmRecord;
import com.wisdytech.linkdcs.equipment.model.Client;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.service.IEquipmentDataService;
import com.wisdytech.linkdcs.equipment.vo.EquipmentAutoAlarmVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentDataVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentHistoryDataVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentRealDataDetailVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentRealDataVO;
import org.springframework.web.client.RestTemplate;

@Service("equipmentDataService")
@Transactional
public class EquipmentDataServiceImpl extends BaseService<IEqClientDao, Client>  implements IEquipmentDataService {
	
	
	private static Logger logger =LoggerFactory.getLogger(EquipmentDataServiceImpl.class);
    
    @Autowired
    private IEqAutoAlarmRecordDao autoRecordDao;
    
    @Autowired
    private IEqEquipmentDao equipmentDao;
    
    @Autowired
    private IEqCollectionParamDao paramDao;

    /**restful服务*/
    @Autowired
    private RestTemplate restTemplate;

    /**主地址*/
    @Value("${restful.baseUrl}")
    private String baseUrl;
    @Value("${restful.getEqRealData}")
    private String getEqRealData;
    
    @Resource
    ThriftClient thriftClient;
    
    @Override
    public PageInfo<EquipmentAutoAlarmVO> listAutoAlarm(Filter filter, EquipmentAuoAlarmDTO dto) {
        
        //分页查找相关参数信息
        List<EquipmentAutoAlarmVO> lists=
                super.beforeList(IEqCollectionParamDao.class, filter).selectParamAutoAlarm(dto);
        
        PageInfo<EquipmentAutoAlarmVO> autoAlarmVOList=new PageInfo<>(lists);
        
        
        return autoAlarmVOList;
    }

    @Override
    public PageInfo<EquipmentDataVO> listRealData(Filter filter, String eqCode, String modelCode) {
        
        Map<String,String> params =new HashMap<>();
        if(StringUtils.isNotBlank(eqCode)){
            params.put("eqCode", eqCode);
        }
        if(StringUtils.isNotBlank(modelCode)){
            params.put("modelCode", modelCode);
        }
        
        List<EquipmentDataVO>  datas=
                super.beforeList(IEqEquipmentDao.class, filter).selectEqRealData(params);
        
        PageInfo<EquipmentDataVO> pageInfo =new PageInfo<>(datas);
        
        
        return pageInfo;
    }

    @Override
    public PageInfo<AutoAlarmRecord> listAutoAlarmDetail(Filter filter, String equipCode, String paramCode,String startTime,String endTime) {
       
        Map<String,Object> params =new HashMap<>();
        if(StringUtils.isNotBlank(equipCode)){
            params.put("equipCode", equipCode);
        }
        if(StringUtils.isNotBlank(paramCode)){
            params.put("paramCode", paramCode);
        }
        
        if(StringUtils.isNotBlank(startTime)){
            params.put("startTime", startTime);
        }
        if(StringUtils.isNotBlank(endTime)){
            params.put("endTime", endTime);
        }
        
        List<AutoAlarmRecord>  datas =
                super.beforeList(IEqAutoAlarmRecordDao.class, filter).listAutoAlarmDetail(params);
        PageInfo<AutoAlarmRecord> pageInfo =new PageInfo<>(datas);
        
        return pageInfo;
    }

    @Override
    public EquipmentRealDataVO listRealData(String id, List<CollectionParam> params) {

        EquipmentRealDataVO result =new EquipmentRealDataVO();
        List<EquipmentRealDataDetailVO> datas = new ArrayList<>();
        StringBuilder sb =new StringBuilder();
        for(CollectionParam cp : params){
            sb.append(cp.getParamCode()).append(",");
        }
        //获取设备
        Equipment equip = equipmentDao.selectById(id);
        System.out.println(baseUrl+"/equipment/getEquipRealData?code="+equip.getEquipCode()
                + "&params="    +sb.toString().substring(0,sb.toString().length()-1));
        //获取数据
        String dataS= restTemplate.getForObject(baseUrl+"/equipment/getEquipRealData?code="+equip.getEquipCode()
                + "&params="+sb.toString().substring(0,sb.toString().length()-1), String.class);
        
        StandardMsgResult<EquipDataDto> msgResult =JSON.parseObject(dataS, new TypeReference<StandardMsgResult<EquipDataDto>>() {});
        EquipDataDto eqDataDto = msgResult.getData();
        //数据时间
        if(eqDataDto.getTime()!=0) {
        	result.setTime(eqDataDto.getTime());
        }else {
        	result.setTime(System.currentTimeMillis());
        }

        for(CollectionParam cParam : params){
            EquipmentRealDataDetailVO vo = new EquipmentRealDataDetailVO();
            vo.setName(cParam.getParamName());
            if(null != eqDataDto.getParamDatas().get(0).getValue()){
                vo.setValue(eqDataDto.getParamDatas().get(0).getValue());
            }else {
                vo.setValue("0.00");
            }
            vo.setRange(cParam.getProcessRange());
            vo.setStartValue(cParam.getStartValue());
            vo.setEndValue(cParam.getEndValue());
            datas.add(vo);
        }
//        EquipmentRealData  erData =new EquipmentRealData();
//        TFramedTransport tFramedTransport =null;
//        try {
//        	tFramedTransport=thriftClient.getTransprot();
//
//        	TProtocol protocol=new TBinaryProtocol(tFramedTransport);
//            LinkDCSService.Client client =new LinkDCSService.Client(protocol);
//            erData =client.getEquipmentRealData(id, paramStr);
//
//		}catch (Exception e) {
//			logger.error("查询实时数据失败", e);
//		} finally {
//			if(null != tFramedTransport) {
//				thriftClient.close(tFramedTransport);
//			}
//		}
//
//
//        //数据时间
//        if(erData.time!=0) {
//        	result.setTime(erData.time);
//        }else {
//        	result.setTime(System.currentTimeMillis());
//        }
//
//
//
//        //查询对应的参数数值
//        for(CollectionParam cParam : params){
//            EquipmentRealDataDetailVO vo = new EquipmentRealDataDetailVO();
//            vo.setName(cParam.getParamName());
//            vo.setRange(cParam.getProcessRange());
//
//
//            if(null != erData.values
//            		&& erData.values.containsKey(cParam.getPkId())){
//                vo.setValue(erData.values.get(cParam.getPkId()));
//            }else {
//            	vo.setValue(0.00);
//            }
//
//
//            vo.setStartValue(cParam.getStartValue());
//            vo.setEndValue(cParam.getEndValue());
//
//            datas.add(vo);
//        }
        
        result.setParamReal(datas);

        return result;
    }

    @Override
    public List<EquipmentHistoryDataVO> listHistoryDetail(EquipHistorySearchDTO dto) throws ParseException {
        
        List<EquipmentHistoryDataVO> result =new ArrayList<>();


        //设备id和参数不能为空
        if(StringUtils.isBlank(dto.getEqId())|| StringUtils.isBlank(dto.getParamId())){
            return result;
        }
        
        //获取设备详情
        Equipment  equipment =
                equipmentDao.selectByEquipCode(dto.getEqId());
        //获取参数详情
        CollectionParam  param =
                paramDao.selectById(dto.getParamId());
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start=dto.getStartTime();
        Date date1 = format.parse(start);
        long l1 = date1.getTime();
        String end=dto.getEndTime();
        Date date2 = format.parse(end);
        long l2 = date2.getTime();
        String dataS =  restTemplate.getForObject(baseUrl+"/equipment/getEquipHisData?"
                        + "equipCode="+equipment.getEquipCode()
                        + "&paramId="+dto.getParamId()
                        + "&paramCode="+param.getParamCode()
                        + "&startTime="+l1
                        + "&endTime="+l2
                        + "&order="+0
                        + "&num="+dto.getNum()
                        + "&size=" +dto.getSize()
                , String.class);
        StandardMsgResult<HisDataDto> msgResult =JSON.parseObject(dataS, new TypeReference<StandardMsgResult<HisDataDto>>() {});
        HisDataDto<EquipDataDto> hisDataDto =  msgResult.getData();
        List<EquipDataDto> list= hisDataDto.getRows();
        //循环补充返回数据
        for(EquipDataDto eqDatadto : list) {
            EquipmentHistoryDataVO vo =new EquipmentHistoryDataVO();
            vo.setEqCode(equipment.getEquipCode());
            vo.setEqName(equipment.getEquipName());
            vo.setModelCode(equipment.getModelCode());
            vo.setOpName(equipment.getOperationName());
            vo.setParamName(param.getParamName());
            vo.setParamRange(param.getProcessRange());
            vo.setEqType(equipment.getModelType());
            vo.setDate(new Date(eqDatadto.getTime()));
            vo.setValue(eqDatadto.getParamDatas().get(0).getValue());
            vo.setSpcValue(param.getSpcValue().doubleValue());
            result.add(vo);
        }

        return result;

//        TFramedTransport tFramedTransport =null;
//        try {
//
//
//        	Date startTime =DateUtil.getDate(dto.getStartTime());
//            Date endTime =DateUtil.getDate(dto.getEndTime());
//            String startKey="";
//            OrderType type ;
//
//            switch(dto.getOrder()){
//            //倒序 即反向查询 上一步
//            case "desc":
//                startKey=dto.getLeftKey();
//                type=OrderType.desc;
//                break;
//            default:
//                //顺序
//                startKey=dto.getRightKey();
//                type=OrderType.asc;
//                break;
//            }
//
//            List<EquipmentHistoryData> eqDatas =new ArrayList<>();
//
//
//
//            tFramedTransport=thriftClient.getTransprot();
//        	TProtocol protocol=new TBinaryProtocol(tFramedTransport);
//            LinkDCSService.Client client =new LinkDCSService.Client(protocol);
//
//
//            int size =dto.getSize()<0?Integer.MAX_VALUE: CommonConstants.HBASE_SEARCH_SIZE;
//
//            eqDatas=client.getEquipmentHistoryDetailData(equipment.getPkId(), dto.getParamId(),
//                    startTime.getTime(), endTime.getTime(), startKey, type, size);
//
//
//
//            //补充信息
//            String previousKey="";
//            /**下一页key*/
//            String nextKey="";
//
//            //有下一条
//            if(eqDatas.size()>=CommonConstants.HBASE_SEARCH_SIZE){
//                nextKey=eqDatas.get(CommonConstants.HBASE_SEARCH_SIZE-1).getRowKey();
//            }
//
//
//            //循环补充设备信息
//            for(int i=0;i<eqDatas.size();i++){
//                EquipmentHistoryData historyData =eqDatas.get(i);
//                //上一页key
//                if(i==0){
//                    previousKey=historyData.getRowKey();
//                    continue;
//                }
//
//                EquipmentHistoryDataVO vo =new EquipmentHistoryDataVO();
//                vo.setEqCode(equipment.getEquipCode());
//                vo.setEqName(equipment.getEquipName());
////                vo.setEqType(equipment.gete);
//                vo.setModelCode(equipment.getModelCode());
//                vo.setOpName(equipment.getOperationName());
//                vo.setParamName(param.getParamName());
//                vo.setParamRange(param.getProcessRange());
//
//
//                vo.setValue(BaseUtil.getDecimal(historyData.getValue(), 2));
//
//
//                vo.setDate(new Date(historyData.getTime()));
//                result.add(vo);
//            }
//
//
//            tableResult.setNextKey(nextKey);
//            tableResult.setPreviousKey(previousKey);
//
//
//
//		}catch (Exception e) {
//			logger.error("查询实时数据失败", e);
//		} finally {
//			if(null != tFramedTransport) {
//				thriftClient.close(tFramedTransport);
//			}
//		}
        
        

    }
    
}
